package com.malbbmsomanager.onlinereports;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.malbbmsomanager.receipt.DM_BBM_InvoiceSalesReceipt;
import com.malbbmsomanagerdemo.DM_BBM_InvoiceMenu;
import com.malbbmsomanagerdemo.R;

public class DM_BBM_Online_Report_Generator extends Activity implements
		OnClickListener, ActionBar.OnNavigationListener {

	// Widget GUI
	private RadioGroup mRadioGroup;
	// Widget GUI
	RadioGroup rgOpinion;
	// action bar
	private ActionBar actionBar;
	
	Button ReportFromDate,ReportToDate,generatereport,selectreportmonth;
	
	int FromToDay = 100;
	String MonthIndex,MonthName;
	
	static final int DATE_DIALOG_ID_FROM = 0;
	
	private int mYear, mMonth, mDay, mHour, mMinute;
	
	String StrSelectedMonth,StrFromDate,StrToDate,currentSalesRep,currentDatabase,baseServerUrl,basePortVal,slectedMenuOption;
	
	Date dateFrom,dateTo;
	
	AlertDialog InvoiceHeaderAlert = null;
	
	public DM_BBM_Online_Report_Generator() {
		// Assign current Date and Time Values to Variables
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		mHour = c.get(Calendar.HOUR_OF_DAY);
		mMinute = c.get(Calendar.MINUTE);
	}
	
	SimpleDateFormat originalFormatTxn = new SimpleDateFormat("dd-MM-yyyy");
	SimpleDateFormat targetFormatTxn = new SimpleDateFormat("yyyy-MM-dd");
	private SQLiteDatabase mydb;
	private static final String DATABASE_NAME = "dminvoicemanagerbbm.db";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_online_report_generator);

		
		
		actionBar = getActionBar();
		// Hide the action bar title
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(false);
		// Init Widget GUI
		rgOpinion = (RadioGroup) findViewById(R.id.rgOpinion);
		generatereport = (Button) findViewById(R.id.generatereport);
		// Attached Click listener to Button
		generatereport.setOnClickListener(this);
	
		ReportFromDate = (Button) findViewById(R.id.selectfromdate);
		selectreportmonth  = (Button) findViewById(R.id.selectreportmonth);
		ReportFromDate.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// Show the DatePickerDialog
				FromToDay = 100;
				showDialog(DATE_DIALOG_ID_FROM);
			}
		});
		
		ReportToDate = (Button) findViewById(R.id.selecttodate);
		ReportToDate.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// Show the DatePickerDialog
				FromToDay = 200;
				showDialog(DATE_DIALOG_ID_FROM);
			}
		});
		
		
		selectreportmonth.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(final View view) {
				// TODO Auto-generated method stub
				PopupMenu popup = new PopupMenu(DM_BBM_Online_Report_Generator.this, selectreportmonth);
				popup.getMenuInflater().inflate(R.menu.dm_months, popup.getMenu());
				
				popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
					@Override
					public boolean onMenuItemClick(MenuItem item) {
						// TODO Auto-generated method stub
						slectedMenuOption = item.getTitle().toString();
						String[] checkoutDateArr = slectedMenuOption.trim().split("-");
						MonthIndex = checkoutDateArr[0];
						MonthName = checkoutDateArr[1];
						selectreportmonth.setText(MonthName);
						return false;
					}
				});
				popup.show();
			}
		});
	}
	
	
	private void getConnectionUrl() {
		// TODO Auto-generated method stub
		Cursor selectUrl = null;
		String selectUrlDetails;
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		selectUrlDetails = "SELECT serverurl,portval FROM serverinfo";
		selectUrl = mydb.rawQuery(selectUrlDetails, null);
		
		if (selectUrl != null) {
			if (selectUrl.getCount() > 0) {
				while (selectUrl.moveToNext()) {
					baseServerUrl = selectUrl.getString(0);
					basePortVal = selectUrl.getString(1);
				}
			}
		}
	}

	private void getCurrentSalesRep() {
		// TODO Auto-generated method stub
		Cursor selectUser = null;
		String selectUserDetails;
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		
		selectUserDetails = "SELECT username,serverDbName FROM usersettings";
		selectUser = mydb.rawQuery(selectUserDetails, null);
		
		if (selectUser != null) {
			if (selectUser.getCount() > 0) {
				while (selectUser.moveToNext()) {
					currentSalesRep = selectUser.getString(0);
					currentDatabase = selectUser.getString(1);
				}
			}
		}
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == generatereport) {
			
			if(ReportFromDate.getText().toString().length() !=0 && ReportToDate.getText().toString().length()!=0){
				// Show the DatePickerDialog
				StrFromDate  = ReportFromDate.getText().toString();
				StrToDate = ReportToDate.getText().toString();
				
				try {
					dateFrom = originalFormatTxn.parse(StrFromDate);
					dateTo = originalFormatTxn.parse(StrToDate);
					StrFromDate = targetFormatTxn.format(dateFrom);
					StrToDate = targetFormatTxn.format(dateTo);
				} catch (ParseException ex) {
					StrFromDate = "1900-01-01";
					StrToDate = "2018-01-01";
				}
				
			}
			else{
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_BBM_Online_Report_Generator.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("INVALID DATE");
				// Setting Dialog Message
				alertDialog.setMessage("Please Select Report Start Date & End Date...");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						alertDialog.dismiss();
					}
				});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			}
			
			if(selectreportmonth.getText().toString().length() !=0){
				StrSelectedMonth  = selectreportmonth.getText().toString();
				StrSelectedMonth = StrSelectedMonth.substring(0, 3);
				//StrSelectedMonth = StrSelectedMonth.toUpperCase();
			}
					
			
			

			// Get Selected Radio Button and display output
			RadioButton selectRadio = (RadioButton) findViewById(rgOpinion
					.getCheckedRadioButtonId());
			String SelectedOption = selectRadio.getText().toString();

			if (SelectedOption.equals("Daily Sales Report")) {
				Intent myIntent = new Intent(
						DM_BBM_Online_Report_Generator.this,
						DM_BBM_Daily_Sales_Report_Online.class);
				myIntent.putExtra("STARTFROMDATE", StrFromDate);
				myIntent.putExtra("STARTTODATE", StrToDate);
				startActivity(myIntent);
				
			} else if (SelectedOption.equals("Monthly Sales Report")) {
				Intent myIntent = new Intent(
						DM_BBM_Online_Report_Generator.this,
						DM_BBM_Monthly_Sales_Report_Online.class);
				myIntent.putExtra("STARTFROMDATE", StrFromDate);
				myIntent.putExtra("STARTTODATE", StrToDate);
				myIntent.putExtra("REPORTMONTH", StrSelectedMonth);
				startActivity(myIntent);

			} else if (SelectedOption.equals("Customer Wise Sales Report")) {
				Intent myIntent = new Intent(
						DM_BBM_Online_Report_Generator.this,
						DM_BBM_Customer_Wise_Sales_Report_Online.class);
				myIntent.putExtra("STARTFROMDATE", StrFromDate);
				myIntent.putExtra("STARTTODATE", StrToDate);
				startActivity(myIntent);

			} else if (SelectedOption.equals("Daily Collection Report")) {
				Intent myIntent = new Intent(
						DM_BBM_Online_Report_Generator.this,
						DM_BBM_Daily_Collection_Report_Online.class);
				myIntent.putExtra("STARTFROMDATE", StrFromDate);
				myIntent.putExtra("STARTTODATE", StrToDate);
				startActivity(myIntent);

			} else if (SelectedOption.equals("Monthly Collection Report")) {
				Intent myIntent = new Intent(
						DM_BBM_Online_Report_Generator.this,
						DM_BBM_Monthly_Collection_Report_Online.class);
				myIntent.putExtra("STARTFROMDATE", StrFromDate);
				myIntent.putExtra("STARTTODATE", StrToDate);
				startActivity(myIntent);

			} else if (SelectedOption.equals("Outstanding Report")) {
				Intent myIntent = new Intent(
						DM_BBM_Online_Report_Generator.this,
						DM_BBM_Outstanding_Report_Online.class);
				myIntent.putExtra("STARTFROMDATE", StrFromDate);
				myIntent.putExtra("STARTTODATE", StrToDate);
				startActivity(myIntent);

			}

		}
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_actions, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_search:
			// search action
			return true;
		case R.id.action_location_found:
			// location found
			BackAction();
			return true;
		case R.id.action_refresh:
			// refresh
			return true;
		case R.id.action_help:
			// help action
			return true;
		case R.id.action_check_updates:
			// check for updates action
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void BackAction() {
		// TODO Auto-generated method stub
		Intent i = new Intent(DM_BBM_Online_Report_Generator.this,
				DM_BBM_InvoiceMenu.class);
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(i);
		finish();
		return;
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DATE_DIALOG_ID_FROM:
			// create a new DatePickerDialog with values you want to show
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);

		}
		return InvoiceHeaderAlert;
	}

	
	// Register DatePickerDialog listener
		private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
			// the callback received when the user "sets" the Date in the
			// DatePickerDialog
			public void onDateSet(DatePicker view, int yearSelected,
					int monthOfYear, int dayOfMonth) {
				mYear = yearSelected;
				mMonth = monthOfYear + 1;
				mDay = dayOfMonth;
				String mMonthStr = Integer.toString(mMonth);
				String mDayStr = Integer.toString(mDay);
				if (mMonthStr.length() == 1) {
					mMonthStr = "0" + mMonthStr;
				}
				if (mDayStr.length() == 1) {
					mDayStr = "0" + mDayStr;
				}
				if(FromToDay == 100){
					ReportFromDate.setText(mDayStr + "-" + mMonthStr + "-" + mYear);
				}
				else if(FromToDay == 200){
					ReportToDate.setText(mDayStr + "-" + mMonthStr + "-" + mYear);
				}
				mMonth = mMonth - 1;
			}
		};

		
}
